/**
 * Authentication Service
 * Handles user authentication, token management, and API integration
 */

const API_BASE_URL = 'http://127.0.0.1:8687';

export const AuthService = {
  /**
   * Login user with username and password
   * @param {string} username - User's username
   * @param {string} password - User's password
   * @returns {Promise<Object>} API response with user data and token
   */
  async login(username, password) {
    try {
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: `${API_BASE_URL}/login`,
          method: 'POST',
          data: {
            username,
            password
          },
          header: {
            'Content-Type': 'application/json'
          },
          timeout: 10000,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            console.error('Login request failed:', err);
            if (err.errMsg && err.errMsg.includes('timeout')) {
              reject(new Error('请求超时，请重试'));
            } else {
              reject(new Error('网络连接失败，请检查网络设置'));
            }
          }
        });
      });

      const { data, statusCode } = response;

      if (statusCode !== 200) {
        throw new Error('服务器响应异常');
      }

      if (data.code === 200) {
        // Store token and user info on successful login
        this.setToken(data.data.token);
        this.setUserInfo(data.data);
        return data;
      } else {
        throw new Error(data.msg || '登录失败');
      }
    } catch (error) {
      console.error('Login error:', error);
      throw error;
    }
  },

  /**
   * Register new user
   * @param {string} username - User's username
   * @param {string} password - User's password
   * @param {string} phone - User's phone number
   * @returns {Promise<Object>} API response
   */
  async register(username, password, phone) {
    try {
      const response = await new Promise((resolve, reject) => {
        uni.request({
          url: `${API_BASE_URL}/register`,
          method: 'POST',
          data: {
            username,
            password,
            phone
          },
          header: {
            'Content-Type': 'application/json'
          },
          timeout: 10000,
          success: (res) => {
            resolve(res);
          },
          fail: (err) => {
            console.error('Register request failed:', err);
            if (err.errMsg && err.errMsg.includes('timeout')) {
              reject(new Error('请求超时，请重试'));
            } else {
              reject(new Error('网络连接失败，请检查网络设置'));
            }
          }
        });
      });

      const { data, statusCode } = response;

      if (statusCode !== 200) {
        throw new Error('服务器响应异常');
      }

      if (data.code === 200) {
        return data;
      } else {
        throw new Error(data.msg || '注册失败');
      }
    } catch (error) {
      console.error('Register error:', error);
      throw error;
    }
  },

  /**
   * Logout user and clear stored data
   */
  logout() {
    try {
      uni.removeStorageSync('auth_token');
      uni.removeStorageSync('user_info');
    } catch (error) {
      console.error('Logout error:', error);
    }
  },

  /**
   * Get stored authentication token
   * @returns {string|null} Authentication token
   */
  getToken() {
    try {
      return uni.getStorageSync('auth_token') || null;
    } catch (error) {
      console.error('Get token error:', error);
      return null;
    }
  },

  /**
   * Set authentication token in storage
   * @param {string} token - Authentication token
   */
  setToken(token) {
    try {
      uni.setStorageSync('auth_token', token);
    } catch (error) {
      console.error('Set token error:', error);
    }
  },

  /**
   * Get stored user information
   * @returns {Object|null} User information
   */
  getUserInfo() {
    try {
      return uni.getStorageSync('user_info') || null;
    } catch (error) {
      console.error('Get user info error:', error);
      return null;
    }
  },

  /**
   * Set user information in storage
   * @param {Object} userInfo - User information object
   */
  setUserInfo(userInfo) {
    try {
      uni.setStorageSync('user_info', userInfo);
    } catch (error) {
      console.error('Set user info error:', error);
    }
  },

  /**
   * Check if user is authenticated
   * @returns {boolean} Authentication status
   */
  isAuthenticated() {
    const token = this.getToken();
    return !!token;
  }
};